package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.TestSchedule")
public class TestSchedule {

    // 如何让每周四 18:00:00 定时执行任务
    public static void main(String[] args) {
        //当前时间
        final LocalDateTime now = LocalDateTime.now();
        System.out.println(now);

        //设置周四时间
//        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);

        //最近运行时间测试
        LocalDateTime time = now.withHour(22).withMinute(38).withSecond(0).withNano(0).with(DayOfWeek.TUESDAY);
        System.out.println(time);

        // 如果当前时间 > 本周四，必须找到下周四
        if(now.compareTo(time)>0){
            time = time.plusWeeks(1);
        }
        System.out.println(time);

        long initialDelay = Duration.between(now, time).toMillis();
        long period = 1000;

        final ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(()->{
            log.debug("running...");
        },initialDelay,period,TimeUnit.MILLISECONDS);
    }
}
